package com.taobao.askwho.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.taobao.askwho.ao.ComplexAo;
import com.taobao.askwho.utils.data.UrlCatcher;
import com.taobao.askwho.vo.ResultPo;

@Controller                 
@RequestMapping("/urlopt.do")
public class UrlAction extends BaseAction {
	Logger logger = Logger.getLogger(UrlAction.class);
	
	@RequestMapping(params = "method=addNewUrl")
	public void addNewUrl(String urlContent, boolean isPublic, String tagString, String userUuid, 
			HttpServletResponse response){
		ResultPo po = new ResultPo();
		if(userUuid == null || userUuid.trim().equals("")) {
			po.setSuccess(false);
			po.setMsg("无用户信息");
			try {
				this.writeJSONToResponseJSONObject(response, po);
			} catch (IOException e) {
				logger.error("", e);
			}
			return;
		}
		
		po = addUrl(urlContent,isPublic,tagString,userUuid);
		
		try {
			this.writeJSONToResponseJSONObject(response, po);
		} catch (IOException e) {
			logger.error("", e);
		}
	}
	
	private ResultPo addUrl(String urlContent, boolean isPublic, String tagString, String userUuid) {
		final ResultPo po = new ResultPo();
		if(tagString == null)
			tagString = "暂无标签";
		else {
			tagString = tagString.trim();
			tagString = tagString.replace('，', ',');
		}
		
		//String[] tagNameArray = tagString.trim().split(",");
		String[] tagNameArray = new String[]{tagString};
		try {
			ComplexAo.get().addNewUrl(urlContent, isPublic, tagNameArray, userUuid);
			po.setSuccess(true);
		} catch (Exception e) {
			logger.error("", e);
			po.setSuccess(false);
			po.setMsg(e.getMessage());
		}
		return po;
	}
	
	@RequestMapping(params = "method=addNewUrlBySystem")
	public void addNewUrlBySystem(HttpServletResponse response){
		Map<String, String> map = new HashMap<String, String>();
		String prefix = "F:\\data\\askwhodata\\url\\";
		String[] fileArray = new String[]{
				"阿里味儿 - Alibaba Group.htm",
				"阿里味儿 - Alibaba Group2.htm",
				"淘宝之家.txt",
				"淘宝之家内网常用url.txt",
				"淘宝直接域名老版本.txt",
				"内网导航全部版.htm",
				"b2b内网链接.txt",
				"pesystem.txt",
				"scm链接.txt",
				"个人工具页面.txt"
		};
		for(String fileName: fileArray) {
			UrlCatcher.readUrlFromFile(prefix + fileName, map);
		}
		UrlCatcher.displayMap(map);
		System.out.println("共加入" + map.size() + "条数据。");
		for(Entry<String, String> entry :map.entrySet()) {
			addUrl(entry.getValue(), true, entry.getKey(), "url_uuid");
		}
		this.writeHTMLToResponse("ok", response);
	}
}
